<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Facades\ObjectStorage;

class CommonController extends Controller{

    //定义允许上传的文件扩展名
    const EXT_ARR = [
        'pic' => ['gif', 'jpg', 'jpeg', 'png', 'bmp'],
        'media' => ['swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'],
        'file' => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2', 'msi','exe'],
    ];


    public function imgUpload(Request $request){
       
        //获取上传文件
        $file = $request->file('file');
        $is_cos = $request->input('is_cos', 1);

        if ($file == null || !$file->isValid()) {
            return response()->json(['code' => 10001, 'message' => 'Picture upload failed']);
        }

        //检查上传错误
        $upload_error_code = $file->getError();
        if (!empty($upload_error_code)) {
            switch($upload_error_code){
                case 1:
                    $error = '超过允许上传的大小。';   // 配置项
                    break;
                case 2:
                    $error = '超过表单允许上传的大小';   // 表单设置
                    break;
                case 3:
                    $error = '图片只有部分被上传';
                    break;
                case 4:
                    $error = '请选择图片';
                    break;
                case 5:
                    $error = '找不到临时目录';
                    break;
                case 6:
                    $error = '写文件到硬盘出错';
                    break;
                case 8:
                    $error = 'File upload stopped by extension';
                    break;
                case 999:
                default:
                    $error = '未知错误';
            }
            return response()->json(['code' => 10002, 'message' => $error]);
        }

        //文件上传成功
        if ($file->isValid()) {

            //文件名
            $file_name = $file->getClientOriginalName();

            //获得文件扩展名
            $file_ext = $file->guessExtension();
            if (empty($file_ext)) {
                $file_ext = $file->getClientOriginalExtension();
            }
            if ($file_ext == 'jpeg') {
                $file_ext = 'jpg';
            }
            if (!in_array($file_ext, self::EXT_ARR['pic'])) {
                return response()->json(['code' => 10003, 'message' => '扩展名是[' . $file_ext . ']的文件禁止上传']);
            }

            //文件大小
            $file_size = $file->getClientSize();
            //检查文件名
            if (!$file_name) {
                return response()->json(['code' => 10004, 'message' => '请选择图片']);
            }

            //检查文件大小
            if ($file_size > 12 * 1048576) {
                return response()->json(['code' => 10005, 'message' => '上传图片大小不能大于3M']);
            }

           // $directory =  'upload/' . W_SHOP_ID . '/' . date('Ymd');
           $directory =  'upload/' . date('Ymd');

            $new_file_name = $this->get_random_string(16) . '.' . $file_ext;

            if ($is_cos != 1) {

                $file->move($directory,  $new_file_name);
                $data = array(
                        'url' => '/'.$directory . '/' . $new_file_name,
                        'name' => $file_name,
                );

                return response()->json(['code' => 200, 'data' => $data]);

            } else {

                //上传
                $upload_data = ObjectStorage::upload($directory . '/' . $new_file_name , $file->getPathname() );
                if ( $upload_data['code'] == 200 ) {
                    $return_data = [
                            'url'=> $upload_data['data'],
                            'name' => $file_name,
                            'size' => $file_size
                    ];
                    return response()->json(['code' => 200,'message'=>'ok', 'data' =>$return_data]);
                } else {
                    return response()->json(['code' => 10006, 'message' => $upload_data['message']]);
                }

            }
        } else {

            return response()->json(['code' => 10010, 'message' => '上传失败']);

        }

    }

    /**
     * 生成任意长度的随机字符串
     * @param int $len 长度
     * @param string $format 格式 mixed：混合 number：数字
     * @return string
     */
    function get_random_string($len, $format = 'mixed')
    {

        if ($format == 'number') {
            $chars = array(
                '0', '1', '2', '3', '5', '6', '7', '8', '9'
            );
        } else {
            $chars = array(
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                'w', 'x', 'y', 'z', '0', '1', '2', '3', '5', '6', '7',
                '8', '9'
            );
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);    // 将数组打乱

        $output = '';
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }

        return $output;

    }





}